package com.yxq.mdt.app.modules.socialcontact.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yxq.mdt.app.BuildConfig;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.glide.GlideHelper;
import com.yxq.mdt.app.model.ShareBean;
import com.yxq.mdt.app.modules.bottomsheet.PublishBottomSheetFragment;
import com.yxq.mdt.app.modules.bottomsheet.ShareSheetDialog;
import com.yxq.mdt.app.modules.personal.bean.PublishResult;
import com.yxq.mdt.app.modules.socialcontact.adapter.MainSocialCircleHeadAdapter;
import com.yxq.mdt.app.modules.socialcontact.adapter.TopicListAdapter;
import com.yxq.mdt.app.modules.socialcontact.bean.CircleTopicListBean;
import com.yxq.mdt.app.modules.socialcontact.bean.MainSocialHeadBean;
import com.yxq.mdt.app.modules.socialcontact.bean.SocialAllListMember;
import com.yxq.mdt.app.modules.socialcontact.model.MainSocialContactModel;
import com.yxq.mdt.app.modules.socialcontact.presenter.MainSocialHomeRecommendPresenter;
import com.yxq.mdt.app.modules.socialcontact.presenter.mainSocialHomeRecommendContract;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.MediaPlayerHelper;

import org.greenrobot.eventbus.EventBus;


import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.Jzvd;

/**
 * 圈子首页
 */
public class CircleTheHomepageAc extends BaseActivity<MainSocialHomeRecommendPresenter> implements mainSocialHomeRecommendContract.View {
    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.circle_image_logo)
    ImageView circleImageLogo;
    @BindView(R.id.circle_nike_name)
    TextView circleNikeName;
    @BindView(R.id.circle_all_number)
    TextView circleAllNumber;
    @BindView(R.id.circle_state_number)
    TextView circleStateNumber;
    @BindView(R.id.circle_text_add)
    TextView circleTextAdd;
    @BindView(R.id.circle_back)
    RelativeLayout circleBack;
    @BindView(R.id.circle_notice)
    TextView circleNotice;
    @BindView(R.id.circle_image_head)
    ImageView circleImageHead;
    @BindView(R.id.circle_nike)
    TextView circleNike;
    @BindView(R.id.circle_member_list)
    RecyclerView circleMemberList;
    @BindView(R.id.circle_all)
    LinearLayout circleAll;
    @BindView(R.id.circle_recycler)
    RecyclerView circleRecycler;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.magic_publish)
    ImageView magicPublish;
    TopicListAdapter circleTopListAdapter;
    MainSocialCircleHeadAdapter mainSocialCircleHeadAdapter;
    PublishBottomSheetFragment publishBottomSheetFragment;
    String topic, groupId;
    int isJoin;

    @Override
    public int getLayoutId() {
        return R.layout.activity_circle_the_homepage;
    }

    public void initView() {
        circleNikeName.setText(getIntent().getStringExtra("CircleName"));
        circleNike.setText(getIntent().getStringExtra("CircleName"));
        groupId = getIntent().getStringExtra("id");

        //头像
        circleMemberList.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false));
        mainSocialCircleHeadAdapter = new MainSocialCircleHeadAdapter(R.layout.item_layout_social_head_list, null);
        circleMemberList.setAdapter(mainSocialCircleHeadAdapter);

        //动态
        circleRecycler.setLayoutManager(new LinearLayoutManager(mActivity));
        circleTopListAdapter = new TopicListAdapter(R.layout.item_layout_dynamic_list, null);
        circleRecycler.setAdapter(circleTopListAdapter);
        circleTopListAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (circleTopListAdapter.countDownTimer != null) {
                circleTopListAdapter.countDownTimer.onFinish();
            }
            Jzvd.releaseAllVideos();
            MediaPlayerHelper.realese();
            Intent it = new Intent(mActivity, SocialStateDetailsAc.class);
            it.putExtra("topicId", circleTopListAdapter.getItem(position).getId());
            it.putExtra("id", circleTopListAdapter.getItem(position).getId());
            startActivity(it);
        });
        circleRecycler.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(@NonNull View view) {

            }


            @Override
            public void onChildViewDetachedFromWindow(@NonNull View view) {
                try {
                    Jzvd jzvd = view.findViewById(R.id.item_social_video_player);
                    if (jzvd != null && Jzvd.CURRENT_JZVD != null && jzvd.jzDataSource.containsTheUrl(Jzvd.CURRENT_JZVD.jzDataSource.getCurrentUrl())) {
                        if (Jzvd.CURRENT_JZVD != null && Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
                            Jzvd.releaseAllVideos();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (circleTopListAdapter.countDownTimer != null) {
                    circleTopListAdapter.countDownTimer.onFinish();
                }
                Jzvd.releaseAllVideos();
                MediaPlayerHelper.realese();
            }
        });
        circleRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (circleTopListAdapter.countDownTimer != null) {
                    circleTopListAdapter.countDownTimer.onFinish();
                    MediaPlayerHelper.pause();
                }
            }
        });
        circleTopListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()) {
                case R.id.item_layout_nike_img:
                    if (circleTopListAdapter.countDownTimer != null) {
                        circleTopListAdapter.countDownTimer.onFinish();
                    }
                    Jzvd.releaseAllVideos();
                    MediaPlayerHelper.realese();
                    Intent it = new Intent(mActivity, SocialPersonalHomepageAc.class);
                    it.putExtra("userId", circleTopListAdapter.getItem(position).getCreateMan());
                    startActivity(it);
                    break;
                case R.id.item_layout_content_browse_img:
                    int giveNum = circleTopListAdapter.getItem(position).getUpCount();
                    if (circleTopListAdapter.getItem(position).getGiveLike() != 0) {
                        MainSocialContactModel.delGsTopicFavour("2", circleTopListAdapter.getItem(position).getId(), new ApiModel.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String s) {
                                circleTopListAdapter.getItem(position).setGiveLike(0);
                                circleTopListAdapter.getItem(position).setUpCount(giveNum - 1);
                                circleTopListAdapter.notifyDataSetChanged();
                                showCenterToast("取消点赞成功");
                            }

                            @Override
                            public void onError(String errMsg) {
                                showCenterToast("取消点赞失败");
                            }
                        });
                    } else {
                        MainSocialContactModel.saveGsTopicFavour(circleTopListAdapter.getItem(position).getId(), "2", new ApiModel.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String s) {
                                circleTopListAdapter.getItem(position).setGiveLike(1);
                                circleTopListAdapter.getItem(position).setUpCount(giveNum + 1);
                                circleTopListAdapter.notifyDataSetChanged();
                                showCenterToast("点赞成功");
                            }

                            @Override
                            public void onError(String errMsg) {
                                showCenterToast("点赞失败");
                            }
                        });
                    }
                    break;
                case R.id.item_layout_attention:
                    TextView attention = view.findViewById(R.id.item_layout_attention);
                    MainSocialContactModel.setInterestRelation(circleTopListAdapter.getItem(position).getCreateMan() + "", 1, 1, new ApiModel.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String s) {
                            attention.setVisibility(View.GONE);
                            showCenterToast("关注成功");
                        }

                        @Override
                        public void onError(String errMsg) {
                            showCenterToast("关注失败");
                        }
                    });
                    break;
                case R.id.item_layout_content_share:
                    //分享
                    ShareBean shareBean = new ShareBean();
                    if (!TextUtils.isEmpty(circleTopListAdapter.getItem(position).getContent())) {
                        shareBean.setTitle(circleTopListAdapter.getItem(position).getContent());//文本
                        shareBean.setText(circleTopListAdapter.getItem(position).getContent());//文本
                    } else {
                        shareBean.setTitle("社交电商新玩法，好玩让你意想不到。");//文本
                        shareBean.setText("社交电商新玩法，好玩让你意想不到。");//文本
                    }
                    shareBean.setShareType("0");//图文分享
                    shareBean.setShareTypeAPP(2);
                    shareBean.setHandleId(circleTopListAdapter.getItem(position).getId());
                    if (circleTopListAdapter.getItem(position).getTopicFileList() != null && circleTopListAdapter.getItem(position).getTopicFileList().size() > 0 && "1".equals(circleTopListAdapter.getItem(position).getTopicFileList().get(0).getClass1())) {
                        shareBean.setImageUrl(circleTopListAdapter.getItem(position).getTopicFileList().get(0).getFile());//LOGO
                    } else {
                        shareBean.setImageUrl("https://yxqoss.oss-cn-hangzhou.aliyuncs.com/gs_app/init/727c432c9e186a11.png");//LOGO
                    }
                    if (!"release".equals(BuildConfig.RELEASE)) {
                        shareBean.setUrl("http://testpm.quai69.com/webtrends.html?topicId=" + circleTopListAdapter.getItem(position).getId() + "&platform=2&parent_id=" + getParentId());//分享URL
                    } else {
                        shareBean.setUrl("http://pm.quai69.com/webtrends.html?topicId=" + circleTopListAdapter.getItem(position).getId() + "&platform=2&parent_id=" + getParentId());
                    }
                    ShareSheetDialog shareSheetDialog = new ShareSheetDialog(shareBean, false);
                    shareSheetDialog.show(getSupportFragmentManager(), "shareSheetDialog");
                    break;
                default:
            }
        });
        circleRecycler.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(@NonNull View view) {

            }

            @Override
            public void onChildViewDetachedFromWindow(@NonNull View view) {
                try {
                    Jzvd jzvd = view.findViewById(R.id.item_social_video_player);
                    if (jzvd != null && Jzvd.CURRENT_JZVD != null &&
                            jzvd.jzDataSource.containsTheUrl(Jzvd.CURRENT_JZVD.jzDataSource.getCurrentUrl())) {
                        if (Jzvd.CURRENT_JZVD != null && Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
                            Jzvd.releaseAllVideos();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (circleTopListAdapter.countDownTimer != null) {
                    circleTopListAdapter.countDownTimer.onFinish();
                }
                Jzvd.releaseAllVideos();
                MediaPlayerHelper.realese();
            }
        });
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            if (mPresenter != null) {
                page = 1;
                mPresenter.getTopList(groupId, 1, 20);
            }
        });
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            if (mPresenter != null) {
                page++;
                mPresenter.getTopList(groupId, page, 20);
            }
        });
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new MainSocialHomeRecommendPresenter(this, new MainSocialContactModel());
        if (mPresenter != null) {
            mPresenter.getRecommendGroupDetail(groupId);
        }
        refreshLayout.autoRefresh();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (circleTopListAdapter.countDownTimer != null) {
            circleTopListAdapter.countDownTimer.cancel();
        }
        Jzvd.releaseAllVideos();
        MediaPlayerHelper.realese();
    }


    @OnClick(R.id.magic_publish)
    public void onViewClicked() {
        if (isJoin == 3) {
            showBottomToast("您还没有加入该圈子");
        } else {
            topic = titlebar.getCenterTextView().getText().toString();
            publishBottomSheetFragment = new PublishBottomSheetFragment("无数据", groupId);
            publishBottomSheetFragment.show(getSupportFragmentManager(), "publishBottomSheetFragment");
        }

    }


    @Override
    public void onLoadRecommendGroupDetailSuccess(MainSocialHeadBean mainSocialHeadBean) {
        if (mainSocialHeadBean != null) {
            setGroupDetail(mainSocialHeadBean);
        } else {
            refreshLayout.finishLoadMoreWithNoMoreData();
        }

    }

    /**
     * 圈子详情
     *
     * @param mainSocialHeadBean
     */
    private void setGroupDetail(MainSocialHeadBean mainSocialHeadBean) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        mainSocialCircleHeadAdapter.setNewData(mainSocialHeadBean.getMenberList());
        titlebar.getCenterTextView().setText(mainSocialHeadBean.getGroupname());
        //群的logo
        GlideHelper.setLoadRoundImage(mActivity, mainSocialHeadBean.getLogo(), R.mipmap.head_icon, circleImageLogo);
        //群主的log
        GlideHelper.setLoadRoundImage(mActivity, mainSocialHeadBean.getOwnerVo().getHeadimg(), R.mipmap.head_icon, circleImageHead);
        //设置背景图
        Glide.with(mActivity).asBitmap().load(mainSocialHeadBean.getBackground()).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                Drawable drawable = new BitmapDrawable(resource);
                circleBack.setBackground(drawable);
            }
        });
        //群主名称
        circleNike.setText(mainSocialHeadBean.getOwnerVo().getUserName());
        circleNikeName.setText(mainSocialHeadBean.getGroupname());
        //当前群员
        circleAllNumber.setText(mainSocialHeadBean.getMenberNum() + "人");
        //发布动态
        circleStateNumber.setText(mainSocialHeadBean.getDynamicNum() + "动态");
        circleNotice.setText("" + mainSocialHeadBean.getDescription());
        isJoin = mainSocialHeadBean.getIsJoin();
        //添加按钮显示隐藏
        switch (mainSocialHeadBean.getIsJoin()) {
            case 3:
                circleTextAdd.setText("加入");
                break;
            case 1:
                circleTextAdd.setText("已加入");
                break;
            case 4:
                circleTextAdd.setText("申请中");
                break;
            default:
        }

        circleTextAdd.setOnClickListener(view -> {
            switch (mainSocialHeadBean.getIsJoin()) {
                case 1:
                    // mPresenter.setIntroductionGroupMembers(mainSocialHeadBean.getId());
                    break;
                case 3:
                    mPresenter.setApplyGroup(mainSocialHeadBean.getId());
                    break;
                case 4:
                    showBottomToast("你的申请正在审核中,请稍后再试");
                    break;
            }
        });
        //去个人主页
        circleImageHead.setOnClickListener(view -> {
            if (circleTopListAdapter.countDownTimer != null) {
                circleTopListAdapter.countDownTimer.onFinish();
            }
            Jzvd.releaseAllVideos();
            MediaPlayerHelper.realese();
            Intent it = new Intent(mActivity, SocialPersonalHomepageAc.class);
            it.putExtra("userId", mainSocialHeadBean.getOwnerVo().getMemberId().replaceAll("yxq", ""));
            startActivity(it);
        });
        //去成员列表界面
        circleAll.setOnClickListener(view -> {
            if (circleTopListAdapter.countDownTimer != null) {
                circleTopListAdapter.countDownTimer.onFinish();
            }
            Jzvd.releaseAllVideos();
            MediaPlayerHelper.realese();
            Intent it = new Intent(mActivity, CircleMemberListAc.class);
            it.putExtra("memberNum", String.valueOf(mainSocialHeadBean.getId()));
            startActivity(it);
        });


    }

    @Override
    public void onLoadRecommendGroupDetailFailed() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
    }

    @Override
    public void onLoadTopListSuccess(CircleTopicListBean circleTopicListBean) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (page == 1) {
            circleTopListAdapter.setNewData(circleTopicListBean.getList());
        } else {
            if (circleTopicListBean.getList() != null && circleTopicListBean.getList().size() != 0) {
                circleTopListAdapter.addData(circleTopicListBean.getList());
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        }
    }

    @Override
    public void onLoadTopListFailed() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();

    }

    @Override
    public void onLoadApplyGroupSuccess(String s) {
        mPresenter.getRecommendGroupDetail(groupId);
    }

    @Override
    public void onLoadApplyGroupFailed() {

    }

    @Override
    public void onLoadIntroductionGroupMembersSuccess(String s) {
        mPresenter.getRecommendGroupDetail(groupId);
    }

    @Override
    public void onLoadIntroductionGroupMembersFailed() {

    }

    @Override
    public void onLoadQueryGroupMembersSuccess(SocialAllListMember socialAllListMember) {

    }

    @Override
    public void onLoadQueryGroupMembersFailed() {

    }

    @Override
    public void onLoadRelationSuccess(String s) {

    }

    @Override
    public void onLoadRelationFailed() {

    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.goOnPlayOnPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.getRecommendGroupDetail(groupId);
        refreshLayout.autoRefresh();
    }
}
